(function() {
	'use strict';

	angular.module('app.plan-entrenamiento')
		.controller('PlantillaPECtrl', ['$scope', '$filter', '$mdDialog', '$mdBottomSheet', 'PlanEntrenamientoService', 'EjerciciosService', PlantillaPECtrl])
		.controller('ListarClientesConPECtrl', ['$scope', '$filter', '$mdDialog', '$state', 'PlanEntrenamientoService', 'UsuariosService', ListarClientesConPECtrl])
		.controller('DetallePECtrl', ['$scope', '$mdDialog', '$stateParams', 'PlanEntrenamientoService', DetallePECtrl]);

	function PEScopeManager (scopeRef2PE, scopeRef2Objetivo) {
		var that = this;

		this.setScopeRef2Objetivo = function(ref) {
			scopeRef2Objetivo = ref;
		};

		this.agregarEjercicio = function(ej) {

			ej.RMT = 0;
			ej.semanas = new Array(8);

			for (var i = 0; i < ej.semanas.length; i++) {
				ej.semanas[i] = {};
				ej.semanas[i].NumeroSemana = i+1;

				if (i<2) {
					ej.semanas[i].Series = scopeRef2Objetivo.SeriesMin;
					ej.semanas[i].Repeticiones = scopeRef2Objetivo.RepeticionesMin;
				} else {
					ej.semanas[i].Series = 0;
					ej.semanas[i].Repeticiones = 0;
				}
				ej.semanas[i].Peso = scopeRef2PE._1RMT*scopeRef2Objetivo.Intenciada;
			}
			scopeRef2PE.ejercicios.push(ej);

			return that;
		};

		this.agregarEjercicios = function(ejercicios) {
			for (var i = 0; i < ejercicios.length; i++) {
				that.agregarEjercicio(ejercicios[i]);
			}
			return that;
		};

		this.borrarEjercicio = function(index) {
			scopeRef2PE.ejercicios.splice(index, 1);
			return that;
		};

		this.esInvalido = function() {
			var invalido = false,
				ejercicios = scopeRef2PE.ejercicios;
			if(ejercicios.length === 0) {
				invalido = true;
			}
			for (var i = 0; i < ejercicios.length && valid; i++) {
				for (var j = 0; j < ejercicios[i].semanas.length && valid; j++) {
					var semana = ejercicios[i].semanas[j];

					if (semana.Series < scopeRef2Objetivo.SeriesMin || semana.Series > scopeRef2Objetivo.SeriesMax) {
						invalido = true;
					} else if (semana.Repeticiones < scopeRef2Objetivo.RepeticionesMin || semana.Repeticiones > scopeRef2Objetivo.RepetionesMax) {
						invalido = true;
					}
				}
			}
			return invalido;
		};

		// Trabajo para poner el scope en un estado valido
		scopeRef2PE.ejercicios = [];
		scopeRef2PE._1RMT = 73.5;
	}

	function PlantillaPECtrl ($scope, $filter, $mdDialog, $mdBottomSheet, PlanEntrenamientoService, EjerciciosService) {
		$scope.planEntrnmento = {};
		$scope.numeroDeSemanas = new Array(8);
		var peScopeManager = new PEScopeManager($scope.planEntrnmento);
		var translator = $filter('translate');




		var isntObjectiveSet = function() {
			if (!$scope.objetivo) {
				$mdDialog.show(
					$mdDialog.alert({
						title: translator('PAGE_PE_PICK_GOAL_FIRST_DIALOG_TITLE'),
						content: translator('PAGE_PE_PICK_GOAL_FIRST_DIALOG_INSTRUCTIONS'),
						ariaLabel: translator('PAGE_PE_PICK_GOAL_FIRST_DIALOG_TITLE'),
						ok: translator('PAGE_PE_PICK_GOAL_FIRST_DIALOG_CTA_OK')
					})
				);
				return true;
			};
			return false;
		};

		var baseWorkoutPlan = function() {
			if (isntObjectiveSet()) {return}

			EjerciciosService.aleatorioPorUbicacion()
			.then(function(response) {
				peScopeManager.agregarEjercicios(angular.fromJson(response.data));
			}, null);
		};

		var addExercise = function() {
			if (isntObjectiveSet()) {return}

			var dialogController = ['$scope','$mdDialog','EjerciciosService', function($scope, $mdDialog, EjerciciosService) {
				EjerciciosService.Listar()
				.then(function(result) {
					$scope.ejercicios = angular.fromJson(result.data);
				}, null);
				$scope.cancel = function() {
					$mdDialog.cancel();
				};
				$scope.confirm = function(ejercicio) {
					$mdDialog.hide(ejercicio);
				};
			}];

			$mdDialog.show({
				controller: dialogController,
				templateUrl: 'views/plan-entrenamiento/seleccionar-ejercicio.tmpl.html'
			})
			.then(function(ejercicio) {
				console.log(ejercicio);
				peScopeManager.agregarEjercicio(ejercicio);
			}, null);
		};

		var chooseGoal = function() {
			var dialogController = ['$scope', '$mdDialog', 'PlanEntrenamientoService',function($scope, $mdDialog, PlanEntrenamientoService) {
				PlanEntrenamientoService.listarObjetivos()
				.then(function(result) {
					$scope.objetivos = angular.fromJson(result.data);
				}, null);
				$scope.cancel = function() {
					$mdDialog.cancel();
				};
				$scope.confirm = function(objetivo) {
					$mdDialog.hide(objetivo);
				};
			}];

			$mdDialog.show({
				controller: dialogController,
				templateUrl: 'views/plan-entrenamiento/seleccionar-objetivo.tmpl.html'
			})
			.then(function(objetivo) {
				console.log(objetivo);
				objetivo.Intenciada = objetivo.IntenciadaMin;
				$scope.objetivo = objetivo;
				peScopeManager.setScopeRef2Objetivo($scope.objetivo);
			}, null);
		};

		var hasErrors = function() {
			if (isntObjectiveSet()) {return}

			if (peScopeManager.esInvalido()) {
				$mdDialog.show(
					$mdDialog.alert({
						title: translator('PAGE_PE_FORMAT_ERROR_DIALOG_TITLE'),
						content: translator('PAGE_PE_FORMAT_ERROR_DIALOG_INSTRUCTIONS'),
						ariaLabel: translator('PAGE_PE_FORMAT_ERROR_DIALOG_TITLE'),
						ok: translator('PAGE_PE_PICK_GOAL_FIRST_DIALOG_CTA_OK')
					})
				);
			};
		};

		var save = function() {
			if (haserrors()) {return}
			var plan = angular.copy($scope.planEntrnmento);
			plan.idObjetivo = $scope.objetivo.Id;
			plan.IdFuncionario = $scope.$root.userInformation.Id;
			console.log(plan);
			//PlanEntrenamientoService.create(plan);
		};




		$scope.openToolBox = function($event) {
			var toolBoxCtrl = ['$scope', '$mdBottomSheet', function($scope, $mdBottomSheet) {
				$scope.items = [
					{
						name: translator('PAGE_PE_CTA_BASE_WORKOUT_PLAN'),
						icon: 'fa-cog',
						onClick: 'baseWorkoutPlan'
					},
					{
						name: translator('PAGE_PE_CTA_ADD_EXERCISE'),
						icon: 'fa-plus',
						onClick: 'addExercise'
					},
					{
						name: translator('PAGE_PE_CTA_CHOOSE_GOAL'),
						icon: 'fa-check-square-o',
						onClick: 'chooseGoal'
					},
					{
						name: translator('PAGE_PE_CTA_SAVE_CHANGES'),
						icon: 'fa-floppy-o',
						onClick: 'save'
					},
					{
						name: translator('PAGE_PE_CTA_CHECK_FOR_ERRORS'),
						icon: 'fa-check',
						onClick: 'hasErrors'
					}
				];
				$scope.listItemClick = function($index) {
					var clickedItem = $scope.items[$index];
					$mdBottomSheet.hide(clickedItem.onClick);
				};
			}];

			$mdBottomSheet.show({
				templateUrl: '/views/plan-entrenamiento/tool-box-button-grid.tmpl.html',
				controller: toolBoxCtrl,
				targetEvent: $event
			}).then(function(clickedItem) {
				switch (clickedItem) {
					case 'baseWorkoutPlan':
						baseWorkoutPlan();
					break;
					case 'addExercise':
						addExercise();
					break;
					case 'chooseGoal':
						chooseGoal();
					break;
					case 'save':
						save();
					break;
					case 'hasErrors':
						hasErrors();
					break;
				}
			});
		};

		$scope.updateWeekSeries = function(exerciseIndex, weekindex, value) {
			console.log(arguments);
			/*$timeout(function() {
				for (var i = 0; i < $scope.planEntrnmento.ejercicios[exerciseIndex].semanas.length; i++) {
					$scope.planEntrnmento.ejercicios[exerciseIndex].semanas[i].Series = value;
				}
			});*/
		};

		$scope.deleteExercise = function(exerciseIndex, weekindex, value) {
			peScopeManager.borrarEjercicio(exerciseIndex);
		};

		chooseGoal();
	}

    function ListarClientesConPECtrl($scope, $filter, $mdDialog, $state, PlanEntrenamientoService, UsuariosService) {
        var init;

        $scope.items = [];
        $scope.filteredItems = [];
        $scope.searchKeywords = '';
        $scope.row = '';
        $scope.numPerPageOpt = [3, 5, 10, 20];
        $scope.numPerPage = $scope.numPerPageOpt[2];
        $scope.currentPage = 1;
        $scope.currentPageItems = [];

        $scope.select = function(page) {
            var end, start;
            start = (page - 1) * $scope.numPerPage;
            end = start + $scope.numPerPage;
            return $scope.currentPageItems = $scope.filteredItems.slice(start, end);
        };

        $scope.onFilterChange = function() {
            $scope.select(1);
            $scope.currentPage = 1;
            return $scope.row = '';
        };

        $scope.onNumPerPageChange = function() {
            $scope.select(1);
            return $scope.currentPage = 1;
        };

        $scope.onOrderChange = function() {
            $scope.select(1);
            return $scope.currentPage = 1;
        };

        $scope.search = function() {
            $scope.filteredItems = $filter('filter')($scope.items, $scope.searchKeywords);
            return $scope.onFilterChange();
        };

        $scope.order = function(rowName) {
            if ($scope.row === rowName) {
                return;
            }
            $scope.row = rowName;
            $scope.filteredItems = $filter('orderBy')($scope.items, rowName);
            return $scope.onOrderChange();
        };

        $scope.verPEs = function(ev, item) {
            var DialogController = ['$scope', '$mdDialog', function ($scope, $mdDialog) {
				PlanEntrenamientoService.listaClientesConPE(item.Id).then(function(result) {
					$scope.planesEntrenamiento = angular.fromJson(result.data);
				}, null);
				$scope.cancel = function() {
					$mdDialog.cancel();
				};
				$scope.confirm = function(pe) {
					$mdDialog.hide(pe.Id);
				};
            }];

            $mdDialog.show({
                controller: DialogController,
                templateUrl: '/views/plan-entrenamiento/seleccionar-pe-de-cliente.tmpl.html',
                targetEvent: ev,
            })
            .then(function(idPE) {
	            $state.go('PE_x_id', {
	                id: idPE
	            });
            }, null);
        };

        init = function() {
            UsuariosService.listaClientesConPE()
            .then(function(result) {
                $scope.items = angular.fromJson(result.data);
                $scope.search();
                $scope.select($scope.currentPage);
            }, null);
        };

        init();
    }

    function DetallePECtrl ($scope, $mdDialog, $stateParams, PlanEntrenamientoService) {
		$scope.numeroDeSemanas = [];
		$scope.numeroDeSemanas.length = 8;

		$scope.addEjercicio = function(ev) {

			var dialogController = ['$scope', '$mdDialog', 'EjerciciosService', function($scope, $mdDialog, EjerciciosService) {
				EjerciciosService.Listar().then(function(result) {
					$scope.ejercicios = angular.fromJson(result.data);
				}, null);
				$scope.cancel = function() {
					$mdDialog.cancel();
				};
				$scope.confirm = function(ejercicio) {
					$mdDialog.hide(ejercicio);
				};
			}];
			
			$mdDialog.show({
				controller: dialogController,
				templateUrl: 'views/plan-entrenamiento/seleccionar-ejercicio.tmpl.html',
				targetEvent: ev,
			})
			.then(function(ejercicio) {
				ejercicio.semanas = [];
				for (var i = 0; i < 8; i++) {
					ejercicio.semanas.push({
						numSemana: 1,
						Series: 10,
						Repeticiones: 10,
						Peso: 10
					});
				};
				$scope.planEntrnmento.ejercicios.push(ejercicio);
			}, null);
		};

		PlanEntrenamientoService.listarXId($stateParams.id)
		.then(function(result) {
			$scope.planEntrnmento = angular.fromJson(result.data);
			console.log($scope.planEntrnmento);
		}, null);
	}
})();